import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MConst } from './mconst.entity';

@Injectable()
export class MConstService {
  constructor(
    @InjectRepository(MConst)
    private readonly mConstRepository: Repository<MConst>,
  ) {}

  async findValueByName(name: string): Promise<string> {
    return (await this.mConstRepository.findOne({ name })).value;
  }
  async setByName(name: string, value: string): Promise<any> {
    const mConst = await this.mConstRepository.findOne({ name });
    if (!mConst) {
      console.log(name, value);
      await this.mConstRepository.save(
        this.mConstRepository.create({ name, value }),
      );
    }
    return await this.mConstRepository
      .createQueryBuilder()
      .update(MConst)
      .set({ value })
      .where('name=:name', { name })
      .execute();
  }
}
